package com.exam.system.servlet;

import com.exam.system.dao.StudentDAO;
import com.exam.system.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class StudentServlet extends HttpServlet {

    private StudentDAO studentDAO = new StudentDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");

        switch (action) {
            case "profile":
                showProfile(request, response);
                break;
            case "updateInfo":
                updateStudentInfo(request, response);
                break;
            case "updatePassword":
                updatePassword(request, response);
                break;
            case "logout":
                logout(request, response);
                break;
            default:
                response.sendRedirect("error.jsp");
        }
    }

    private void showProfile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String studentId = (String) session.getAttribute("studentId");

        if (studentId != null) {
            Student student = studentDAO.findByStudentId(studentId);
            request.setAttribute("student", student);
            request.getRequestDispatcher("/student/profile.jsp").forward(request, response);
        } else {
            response.sendRedirect("login.jsp");
        }
    }

    private void updateStudentInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 实现更新学生信息逻辑
        response.sendRedirect("student?action=profile");
    }

    private void updatePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 实现更新密码逻辑
        response.sendRedirect("student?action=profile");
    }

    private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        response.sendRedirect("login.jsp");
    }
}